package com.course.system.controller.admin;

import com.course.model.dto.RoleDto;
import com.course.model.dto.PageDto;
import com.course.common.response.BaseResponse;
import com.course.model.util.ValidatorUtil;
import com.course.model.service.RoleService;
import com.course.system.controller.BaseController;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/admin/role")
public class RoleController extends BaseController {

    public static final String BUSINESS_NAME = "角色";

    @Resource
    private RoleService roleService;

    /**
     * 列表查询
     */
    @PostMapping("/getRoleList")
    public BaseResponse list(@RequestBody PageDto pageDto) {
        BaseResponse response = new BaseResponse().sucess();
        roleService.list(pageDto);
        response.setData(pageDto);
        return response;
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    @PostMapping("/save")
    public BaseResponse save(@RequestBody RoleDto roleDto) {
        // 保存校验
        ValidatorUtil.require(roleDto.getName(), "角色");
        ValidatorUtil.length(roleDto.getName(), "角色", 1, 50);
        ValidatorUtil.require(roleDto.getDesc(), "描述");
        ValidatorUtil.length(roleDto.getDesc(), "描述", 1, 100);

        BaseResponse response = new BaseResponse().sucess();
        roleService.save(roleDto);
        response.setData(roleDto);
        return response;
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public BaseResponse delete(@PathVariable String id) {
        BaseResponse response = new BaseResponse().sucess();
        roleService.delete(id);
        return response;
    }

    @PostMapping("/save-resource")
    public BaseResponse saveResource(@RequestBody RoleDto roleDto){
        logger.info("保存角色资源关联开始");
        BaseResponse response = new BaseResponse().sucess();
        roleService.saveResource(roleDto);
        response.setData(roleDto);
        return response;
    }

    @GetMapping("/list-resource/{roleId}")
    public BaseResponse listResource(@PathVariable String roleId){
        logger.info("加载资源开始");
        BaseResponse response = new BaseResponse().sucess();
        response.setData(roleService.listResource(roleId));
        return response;
    }

    @PostMapping("/save-user")
    public BaseResponse saveUser(@RequestBody RoleDto roleDto){
        logger.info("保存角色用户关联开始");
        BaseResponse response = new BaseResponse().sucess();
        roleService.saveUser(roleDto);
        response.setData(roleDto);
        return response;
    }

    @GetMapping("/list-user/{roleId}")
    public BaseResponse listUser(@PathVariable String roleId){
        logger.info("加载用户开始");
        BaseResponse response = new BaseResponse().sucess();
        response.setData(roleService.listUser(roleId));
        return response;
    }
}
